#! /usr/bin/env python
# coding=utf-8
from ctypes import *
from datetime import datetime
from matplotlib import pyplot as plt
import numpy as np

usb_id = 0
dev_addr = 0x80
resistor = 0.1  # ohm
battery_capacity = 3.4*3*1000  # mAh

ch341 = windll.LoadLibrary("./CH341DLLA64.DLL")
if ch341.CH341OpenDevice(usb_id) == -1:
    print("USB CH341 Open Failed!")
    exit(1)
ch341.CH341SetStream(usb_id, 0x83)


def ina219config(dat):
    """change config register in ina219

    Args:
        dat (byte[2]): new conf data
    """
    addr = 0x00
    obuf = (c_byte * 4)()
    ibuf = (c_byte * 1)()
    obuf[0] = dev_addr
    obuf[1] = addr
    obuf[2] = dat[0] & 0xff
    obuf[3] = dat[1] & 0xff
    ch341.CH341StreamI2C(usb_id, 4, obuf, 0, ibuf)


ina219config([0x21, 0x8d])

data_addr = 0x01
rec = (c_ubyte * 2)()
ibuf = (c_ubyte * 2)()
rec[0] = dev_addr
rec[1] = data_addr & 0xff


def read_current():
    ch341.CH341StreamI2C(usb_id, 2, rec, 2, ibuf)
    current = round((ibuf[0] << 8 | ibuf[1])/resistor*0.01, 2)
    if(current > 3.2*1024):
        current = current-6.4*1024
    return current  # mA


sample_time = 1800
POINTS = 300
c_list = [0.0] * POINTS
t_list = [0.0] * POINTS
c_max = 10
cnt = 0
# fig, ax = plt.subplots()
starttime = datetime.timestamp(datetime.now())
while True:
    cnt += 1
    # 更新绘图数据
    c = read_current()
    if(c > c_max):
        c_max = c
    # print(c)
    c_list = c_list[1:] + [c]
    timenow = datetime.timestamp(datetime.now())-starttime
    t_list = t_list[1:] + [timenow]
    # 计算采样率
    if(cnt > POINTS):
        samplerate = POINTS/(t_list[-1]-t_list[0])
        plt.xlabel("time(s) sample rate: "+str(round(samplerate, 2)))
        average = round(sum(c_list)/POINTS, 2)
        plt.title("current vs. time, now:"+str(c)+" avg:"+str(average))
    else:
        plt.xlabel("time(s)")
        plt.title("current vs. time, now:"+str(c))

    # 显示时间
    plt.pause(0.001)
    # 清除上一次显示
    plt.cla()
    average = round(sum(c_list)/POINTS, 2)
    plt.title("current vs. time, now:"+str(c)+" avg:"+str(average))
    plt.ylabel("current(mA)")
    plt.ylim(0, c_max)
    plt.plot(t_list, c_list)
    if(timenow > sample_time):
        break
    # plt.show()如果放在这个位置就会卡住

plt.show()  # 放在最后不会影响之后的代码执行
